package io.seata.factoryservice.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.net.UnknownHostException;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : author
 * @create 2022/8/20 10:08
 */
@Configuration
public class RedisConfiguration {

    //redis序列化器
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());
        return template;
    }

    //声明式缓存序列化器
    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        RedisCacheConfiguration redisCacheConfiguration =
                RedisCacheConfiguration.defaultCacheConfig();
        //修改默认的序列化器
        redisCacheConfiguration = redisCacheConfiguration.
                serializeKeysWith(
                        RedisSerializationContext.SerializationPair.
                                fromSerializer(RedisSerializer.string())).
                serializeValuesWith(
                        RedisSerializationContext.SerializationPair.
                                fromSerializer(RedisSerializer.json())
                );
        return redisCacheConfiguration;
    }
}
